<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>router</title>
    <!-- 导入 vue 文件 -->
    <script src="js/vue.js"></script>
    <script src="js/vue-router.js"></script>
</head>

<body>
    <!-- 被 vm 实例所控制的区域 -->
    <div id="app">
        <router-link to="/user/1">User1</router-link>
        <router-link to="/user/2">User2</router-link>
        <router-link to="{name: 'user', params: {id: 3, username: 'George'}">User3</router-link>
        <router-link to="/register">Register</router-link>

        <!-- 路由占位符 -->
        <router-view></router-view>
    </div>

    <script>
        const User = {
            props: ['id', 'username'],
            template: `
                <div>
                    <h1>User 组件---路由中的 id为： {{id}} ----- 姓名为：{{username}}</h1>
                    <button @click="goRegister">跳转到注册页面</button>
                </div>
            `,
            methods: {
                goRegister() {
                    this.$router.push({ path: '/register', query: { id: "888" } })
                }
            }
        }

        const Register = {
            props: ['id', 'username'],
            template: `
                <div>
                    <h1>Register 组件---id为{{id}}---username为{{username}}</h1>
                    <button @click="goback">回退</button>
                </div>
            `,
            methods: {
                goback() {
                    // 路由回退
                    this.$router.go(-1);
                }
            }
        }

        // 创建路由实例对象
        const router = new VueRouter({
            // 所有路由规则
            routes: [
                { path: "/", redirect: "/user" },
                {
                    path: '/user/:id', name: 'user', component: User, props: route => ({
                        username: 'George', id: route.params.id
                    })
                },
                {
                    path: '/register', component: Register, props: (route) => {
                        return { username: "jack", id: route.query.id }
                    }
                }
            ]
        })

        // 创建 vm 实例对象
        const vm = new Vue({
            // 指定控制的区域
            el: '#app',
            data: {},
            // 挂载路由实例对象
            router
        })
    </script>
</body>

</html>